# Arguments in the following format:
# database=192.68.0.1 appserver=192.168.0.2~192.168.0.3 jms=192.168.0.4 agent=import,search:192.168.0.5~export:192.168.0.6

#variables
JMS_HOSTNAME=<%=@jmshost%>
INSTALL_PATH=<%=@installdir%>/runtime
BIN_PATH=${INSTALL_DIR}/bin
DB_HOSTNAME=<%=@dbhost%>

current_ip=`/sbin/ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
current_ip=`echo $current_ip | cut -d\  -f1`

# Process command line arguments
args=($@)
for i in "${!args[@]}"; do 
  key=`echo ${args[$i]} | cut -d= -f1`
  val=`echo ${args[$i]} | cut -d= -f2`

  case "$key" in
  database) 
  IFS='~' read -a db_ip_arr <<< "${val}"
  ;;
  appserver)
  IFS='~' read -a appserver_ip_arr <<< "${val}"
  ;;
  jms)
  IFS='~' read -a jms_ip_arr <<< "${val}"
  ;;
  agent)
  IFS='~' read -a agent_ip_arr <<< "${val}"
  ;;
  smtp_user)
  read -a smtpuser <<< "${val}"
  ;;
  smtp_password)
  read -a smtppassword <<< "${val}"
  ;;	
  esac 	
done

# Map the database host name
sudo sh -c "echo ${db_ip_arr[0]} $DB_HOSTNAME >>/etc/hosts"

# Map the jms host name
sudo sh -c "echo ${jms_ip_arr[0]} $JMS_HOSTNAME >>/etc/hosts"

# Map the current host name
NEW_HOSTNAME=`hostname`
sudo sh -c "echo ${current_ip} $NEW_HOSTNAME >>/etc/hosts"

# Start the agent servers
for var in "${agent_ip_arr[@]}"
do
  agents=`echo $var | cut -d: -f1`
  ip=`echo $var | cut -d: -f2`
  if [ $ip == $current_ip ]
  then
     IFS=',' read -a agent_name_arr <<< "${agents}"
	 sudo touch ${INSTALL_PATH}/agentservice.cfg
     for var1 in "${agent_name_arr[@]}"
     do
	   sudo sh -c "echo $var1 >> ${INSTALL_PATH}/agentservice.cfg"
     done
  fi
done
   
# Add the agent service in system startup
sudo chkconfig agentservice --add 

# Start all the agents
sudo service agentservice start

sleep 10